package other;

/**
 * @Author: Dang Qi
 * @Date: 2021/4/22 19:35
 * @Description:
 */
public class Sqrt {
    public static void main(String[] args) {
        System.out.println(sqrt2(17));
    }
    public static double sqrt1(double x){
        return sqrt1(x, 0.00001);
    }
    //二分法
    public static double sqrt1(double x, double EPSINON){
        double low = 0.0;
        double high = (x+1)/2;
        double mid = (low + high) / 2;
        while ((high - low) > EPSINON){
            if (mid*mid > x){
                high = mid;
            }
            else{
                low = mid;
            }
            mid = (high + low) / 2;
        }
        return mid;
    }
    //牛顿迭代法
    public static double sqrt2(double x) {
        if (x == 0) {
            return 0;
        }
        double last = 0.0;
        double res = 1.0;
        while (res != last) {
            last = res;
            res = (res + x / res) / 2;
        }
        return res;
    }
}
